package api

import (
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"gitee.com/enzolwb/my-web-scaffold/pkg/upload"
	"github.com/gin-gonic/gin"
)

//  UploadImage 入参 -> 检查 -> 保存
func UploadImage(c *gin.Context) {
	code := ecode.Ok
	data := make(map[string]string)

	file, image, err := c.Request.FormFile("image")
	if err != nil {
		app.Response(c, ecode.ErrRequest.Reload(err.Error()))
		return
	}

	if image == nil {
		code = ecode.ErrRequest
	} else {
		imageName := upload.GetImageName(image.Filename)
		fullPath := upload.GetImageFullPath()
		savePath := upload.GetImagePath()

		src := fullPath + imageName
		if !upload.CheckImageExt(imageName) {
			code = ecode.ERROR_UPLOAD_CHECK_IMAGE_FORMAT
		} else if !upload.CheckImageSize(file) {
			code = ecode.ERROR_UPLOAD_CHECK_IMAGE_SIZE
		} else {
			err := upload.CheckImage(fullPath)
			if err != nil {
				code = ecode.ERROR_UPLOAD_CHECK_IMAGE_FAIL
			} else if err := c.SaveUploadedFile(image, src); err != nil {
				code = ecode.ERROR_UPLOAD_SAVE_IMAGE_FAIL
			} else {
				data["image_url"] = upload.GetImageFullUrl(imageName)
				data["image_save_url"] = savePath + imageName
			}
		}
	}
	app.Response(c, code, data)
}
